<?php

declare(strict_types=1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\GmEmailexa as M;
use app\common\validate\GmEmailexa as V;

class GmEmailexa
{
    // 添加
    public static function goAdd($data)
    {
        //验证
        $validate = new V;
        if (!$validate->scene('add')->check($data))
            return ['msg' => $validate->getError(), 'code' => 201];
        try {
            M::create($data);
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 编辑
    public static function goEdit($data, $id)
    {
        $data['id'] = $id;
        //验证
        $validate = new V;
        if (!$validate->scene('edit')->check($data))
            return ['msg' => $validate->getError(), 'code' => 201];
        try {
            M::update($data);
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 通过
    public static function goPass($data, $id)
    {
        try {
            $model = M::find($id);
            if ($model['exastatus'] == '1' || $model['exastatus'] == '2') {
                return ['msg' => '操作失败,邮件已处理！', 'code' => 201];
            }

            //后面新加的  直播福利
            if ($model['sendtype'] == '6') {
                M::sendEmailPass($model['cmdtxt']);
                $model['exastatus'] = '1';
                $model->save();
                return ['msg' => '操作成功', 'code' => 200];
            } else {
                self::toSendEmail($model);
            }
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 通过
    public static function goPass1($data, $id, $num)
    {
        try {
            $model = M::find($id);
            if ($model['exastatus'] == '1' || $model['exastatus'] == '2') {

                return ['msg' => '操作失败,邮件已处理！', 'code' => 201];
            }
            for ($i = 0; $i < $num; $i++) {
                self::toSendEmail($model);
            }
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    public static function onekeypass($ids)
    {
        if (!is_array($ids)) return ['msg' => '数据不存在', 'code' => 201];
        try {

            foreach ($ids as $id) {
                $model = M::find($id);
                if ($model['exastatus'] == '1' || $model['exastatus'] == '2') {
                    continue;
                }
                //后面新加的  直播福利
                if ($model['sendtype'] == '6') {
                    M::sendEmailPass($model['cmdtxt']);
                    $model['exastatus'] = '1';
                    $model->save();
                } else {
                    self::toSendEmail($model);
                }
            }

            return ['msg' => '操作成功', 'code' => 200];
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }


    public static function toSendEmail($model)
    {

        $address = env('APP_DEBUG') ? config('web')['developmentServer'] : config('web')['productionServer'];
        // 目标 URL
        $url = 'http://' . $address . '/admin/gmexadata.php';
        // POST 请求数据（示例）
        $postData = [
            'hantype' => '1',
            'cmdtxt' => $model['cmdtxt'],
            'content' => $model['content'],
            'exastatus' => $model['exastatus'],
            'exatime' => $model['exatime'],
            'exauser' => $model['exauser'],
            'id' => $model['id'],
            'sendtype' => $model['sendtype'],
            'title' => $model['title'],
            'touser' => $model['touser'],
            'quls' => $model['quls']
        ];

        // 初始化 cURL 会话
        $ch = curl_init($url);

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置为 true，以便获取响应
        curl_setopt($ch, CURLOPT_POST, true); // 发送 POST 请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置 POST 数据

        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);

        // 检查是否发生错误
        if (curl_errno($ch)) {
            return ['msg' => '操作失败,请求本地文件失败！！！', 'code' => 201];
        }

        // 关闭 cURL 会话
        curl_close($ch);
    }

    // 拒绝
    public static function goExit($data, $id)
    {
        $data['id'] = $id;
        $data['exastatus'] = '2';
        try {
            $model = M::find($id);
            if ($data['exastatus']) {
                $model->exastatus = $data['exastatus'];
                $model->token = null;
            }
            $model->save();
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 状态
    public static function goStatus($data, $id)
    {
        $model =  M::find($id);
        if ($model->isEmpty())  return ['msg' => '数据不存在', 'code' => 201];
        try {
            $model->save([
                'status' => $data,
            ]);
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 删除
    public static function goRemove($id)
    {
        $model = M::find($id);
        if ($model->isEmpty()) return ['msg' => '数据不存在', 'code' => 201];
        try {
            $model->delete();
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids)
    {
        if (!is_array($ids)) return ['msg' => '数据不存在', 'code' => 201];
        try {
            M::destroy($ids);
        } catch (\Exception $e) {
            return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
        }
    }

    // 获取列表
    public static function goRecycle()
    {
        if (Request::isPost()) {
            $ids = Request::param('ids');
            if (!is_array($ids)) return ['msg' => '参数错误', 'code' => '201'];
            try {
                if (Request::param('type')) {
                    $data = M::onlyTrashed()->whereIn('id', $ids)->select();
                    foreach ($data as $k) {
                        $k->restore();
                    }
                } else {
                    M::destroy($ids, true);
                }
            } catch (\Exception $e) {
                return ['msg' => '操作失败' . $e->getMessage(), 'code' => 201];
            }
            return ['msg' => '操作成功'];
        }
        //按用户名
        $where = [];
        $limit = input('get.limit');

        //按标题查找
        if ($title = input("title")) {
            $where[] = ["title", "like", "%" . $title . "%"];
        }
        //按内容查找
        if ($content = input("content")) {
            $where[] = ["content", "like", "%" . $content . "%"];
        }
        //按审核状态 0.未审核 1.已审核 2.未通过查找
        if ($exastatus = input("exastatus")) {
            $where[] = ["exastatus", "like", "%" . $exastatus . "%"];
        }
        //按申请时间查找
        $start = input("get.exatime-start");
        $end = input("get.exatime-end");
        if ($start && $end) {
            $where[] = ["exatime", "between", [$start, date("Y-m-d", strtotime("$end +1 day"))]];
        }
        //按发送给谁查找
        if ($touser = input("touser")) {
            $where[] = ["touser", "like", "%" . $touser . "%"];
        }
        //按申请发送人查找
        if ($exauser = input("exauser")) {
            $where[] = ["exauser", "like", "%" . $exauser . "%"];
        }
        $list = M::onlyTrashed()->where($where)->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }
}
